# -*- coding: utf-8 -*-

__author__ = 'parano1d'
__date__ = '08.07.2010 1:22:38'

from UserDict import UserDict
from gestor.database import GestorDatabase

class GestorPackages(GestorDatabase):
    """Contains operations with packages"""

    def __init__(self):
        GestorDatabase.__init__(self)

    def get_full(self):
        """Gets categories, packages, versions and return a nice list
        :return: list of categories (tuples) which contains packages which contains versions"""

        # This method can be more easily done with the help of other python statements
        # Somethink like in comments

        #self.cursor.execute(u"SELECT * FROM `Category`, `Package`, `Version` \
        #        WHERE `Package`.`id_category` = `Category`.`id` AND `Version`.`id_package` = `Package`.`id`")
        #data = self.cursor.fetchall()

        if not self.connected:
            return []

        data = []
        categories = self.get_categories()

        for category in categories:
            category['type'] = 'category'
            packages = self.get_packages(category['id'])

            for package in packages:
                package['type'] = 'package'
                package['versions'] = self.get_versions(package['id'])

                for version in package['versions']:
                    version['type'] = 'version'

            category['packages'] = packages
            data.append(category)

        return data


    def get_packages(self, id_category = None):
        """Gets packages from database
        :param id_category: gets packages only from one category
        :return: list of packages (of class Package)"""

        if not self.connected:
            return []
        
        if id_category:
            sql = u"SELECT * FROM `Package` WHERE `id_category` = %d ORDER BY `title`" % (id_category)
        else:
            sql = u"SELECT * FROM `Package` ORDER BY `title`"

        self.cursor.execute(sql)

        data = self.cursor.fetchall()
        packages = [row for row in data]
        
        return packages

    def get_versions(self, id_package):
        """Gets versions of a package from database
        :param id_package: id of a package
        :return: list of versions of a package"""

        if not self.connected:
            return []

        self.cursor.execute(u"SELECT * FROM `Version` WHERE `Version`.`id_package` = %d ORDER BY `title`" % (id_package))

        data = self.cursor.fetchall()
        versions = [row for row in data]

        return versions

    def get_categories(self):
        """Gets all categories from database
        :return: list of all categories"""

        if not self.connected:
            return []

        self.cursor.execute(u"SELECT * FROM `Category` ORDER BY `title`")

        data = self.cursor.fetchall()
        categories = [row for row in data]

        return categories

    def add_package(self, package):
        """Inserts a new package into database
        :param package: tuple, contains title, description, etc of the package"""

        if not self.connected:
            return 1
        
        if self.cursor.execute(u"INSERT INTO `Package` \
                                 (`title`, `description`, `active`, `id_category`, `site`) \
                                 VALUES ('%s', '%s', '%s', %d, %d, '%s', '%s')" %
                                 (package.title, package.description, package.active, \
                                 package.id_category, package.site)):
            return 0
        else:
            return 1

    def update_package(self, package):
        """Updates the package into database
        :param package: tuple, contains id, title, etc of the package"""

        if not self.connected:
            return 1
        
        sql = ''

        if package.description:
            sql += u", `description` = '%s'" % package.description
        if package.site:
            sql += u", `site` = '%s'" % package.site
        
        if self.cursor.execute(u"UPDATE `Package` SET `title` = '%s', `id_category` = %d%s \
                                 WHERE `id` = %d" % (package.title, \
                                 package.id_category, sql, package.id)):
            return 0
        else:
            return 1

    def del_package(self, id_package):
        """Deletes the package specified by `id_package' from database
        :param id_package: id of a package to delete"""

        if not self.connected:
            return 1

        if self.cursor.execute(u"DELETE FROM `Package` WHERE `id` = %d" % id_package):
            return 0
        else:
            return 1
